<?php

namespace Xibeicity\Message\Drivers;

use Xibeicity\Message\Contracts\MessageInterface;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class AliyunSms implements MessageInterface
{
    protected $config;
    protected $error;

    /**
     * 初始化阿里云短信驱动
     *
     * @param array $config 配置信息
     *                      - access_key_id    阿里云访问密钥ID
     *                      - access_key_secret 阿里云访问密钥密码
     *                      - region_id        地域ID，默认为cn-hangzhou
     *                      - sign_name        短信签名
     *                      - template_code    短信模板ID（可选）
     */
    public function __construct(array $config)
    {
        $this->config = $config;
        
        AlibabaCloud::accessKeyClient($config['access_key_id'], $config['access_key_secret'])
            ->regionId($config['region_id'] ?? 'cn-hangzhou')
            ->asDefaultClient();
    }

    /**
     * 发送短信
     *
     * @param array  $to      接收手机号码数组
     * @param string $content 短信内容
     * @param array  $options 额外选项
     *                       - template_code   短信模板ID
     *                       - template_param  模板参数
     * 
     * @return array 发送结果
     *               - success    是否发送成功
     *               - message_id 消息ID
     */
    public function send(array $to, string $content, array $options = []): array
    {
        try {
            $params = [
                'PhoneNumbers' => implode(',', $to),
                'SignName' => $this->config['sign_name'],
                'TemplateCode' => $options['template_code'] ?? $this->config['template_code'],
                'TemplateParam' => json_encode($options['template_param'] ?? ['content' => $content]),
            ];

            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' => $params,
                ])
                ->request();

            return [
                'success' => $result['Code'] === 'OK',
                'message_id' => $result['RequestId'] ?? null
            ];
        } catch (ClientException | ServerException $e) {
            $this->error = $e->getMessage();
            return [
                'success' => false,
                'message_id' => null
            ];
        }
    }

    /**
     * 使用模板发送短信
     *
     * @param array  $to            接收手机号码数组
     * @param string $templateCode  短信模板ID
     * @param array  $templateParams 模板参数
     * @param array  $options       额外选项
     * 
     * @return array 发送结果
     *               - success    是否发送成功
     *               - message_id 消息ID
     */
    public function sendTemplate(array $to, string $templateCode, array $templateParams = [], array $options = []): array
    {
        $options['template_code'] = $templateCode;
        $options['template_param'] = $templateParams;
        return $this->send($to, '', $options);
    }

    /**
     * 批量发送短信
     *
     * @param array $messages 消息列表
     *                       - to      接收手机号码数组
     *                       - content 短信内容
     *                       - options 额外选项
     * 
     * @return array 每条消息的发送结果数组
     */
    public function batchSend(array $messages): array
    {
        $results = [];
        foreach ($messages as $message) {
            $results[] = $this->send(
                $message['to'],
                $message['content'],
                $message['options'] ?? []
            );
        }
        return $results;
    }

    /**
     * 获取短信发送状态
     *
     * @param string|null $messageId 消息ID
     * 
     * @return array 发送状态
     *               - status 发送状态
     *               - error  错误信息
     */
    public function getStatus(string $messageId = null): array
    {
        return [
            'status' => 'sent',
            'error' => $this->error
        ];
    }

    /**
     * 获取错误信息
     *
     * @return string|null 错误信息
     */
    public function getError(): ?string
    {
        return $this->error;
    }

    /**
     * 获取驱动配置信息
     *
     * @return array 配置信息
     *               - access_key_id 阿里云访问密钥ID
     *               - region_id     地域ID
     *               - sign_name     短信签名
     */
    public function getConfig(): array
    {
        return [
            'access_key_id' => $this->config['access_key_id'],
            'region_id' => $this->config['region_id'] ?? 'cn-hangzhou',
            'sign_name' => $this->config['sign_name']
        ];
    }
}